<template>
    <div class="poster_container">
        <Grouping ref="GroupingRef" :type="posters" :group-id="group_id" @submit="changeGroup">
            <el-tabs v-model="strTabIndex" class="tabs_box" @tab-change="chooseTabIndex">
                <el-tab-pane label="我的海报" name="0" />
                <el-tab-pane label="企业海报" name="1" />
            </el-tabs>
        </Grouping>
        <div class="poster_main">
            <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
            <ZwTable
                ref="myTableRef"
                class="table-box"
                tab-h="initial"
                :option="tableOption"
                :row-key="getRowKey"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()"
                @selection-change="getSelectMyTable">
                <template #headerOperate>
                    <div class="control-btn-box">
                        <el-button v-auth="'BAT_DOW_PT'" :disabled="posterIds.length == 0" @click="batchDown">
                            批量下载
                        </el-button>
                        <el-button v-auth="'BAT_DEL_PT'" :disabled="posterIds.length == 0" @click="delItem">
                            批量删除
                        </el-button>
                        <el-button v-auth="'MAKE_PT'" type="primary" @click="toCreate">制作海报</el-button>
                    </div>
                </template>
            </ZwTable>
            <DeletBox ref="DeletBoxRef" />
        </div>
    </div>
    <PreviewBox ref="PreviewBoxRef" :item-info="itemInfo" />
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'CONTENT_HIHG_MATERIAL_POSTER' });
</script>

<script setup lang="tsx">
import Grouping from '@/components/ZWGroup.vue';
import ZWPagination from '@/components/ZWPagination.vue';
import DeletBox from './components/DeletBox.vue';
import PreviewBox from './components/PreviewBox.vue';

import { posterList, batchDel, batchDownload, downStat } from '@/api/highMaterial/poster';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import { ref, onMounted, nextTick, reactive, computed, onActivated } from 'vue';
import { useStore } from '@/store';
import router from '@/router';
import { useRoute } from 'vue-router';
import { downFile, getSetionId } from '@/utils/utils';
import { deepCopy } from '@/utils/helper';
import { getCreateList } from '@/api/common';
import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus';

const store = useStore();
const route = useRoute();
const posterIds: any = ref([]); //当前选中的数据
const DeletBoxRef: any = ref(null);
const GroupingRef = ref();
const myTableRef: any = ref(null);
const PreviewBoxRef: any = ref(null);
const itemInfo = ref({}); //当前选择的数据
const posters = ref(9);
const tabIndex = ref(0); //当前的海报类型  0  我的海报  1 企业海报
const strTabIndex = ref('0');
const group_id = ref<number | string>('all');
const requestFlag = ref<boolean>(false);
const isOnMountedFlag = ref<boolean>(false);
const currentParams = ref<any>(null);
const defaultParams = reactive({
    poster_title: '',
    create_uid: [],
    create_time: [],
    poster_type: tabIndex.value + 1,
    group_id: group_id.value || 0
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const getRowKey = (row: any) => {
    return row.id;
};
const searchOption = computed(() => {
    return [
        {
            label: '海报搜索',
            name: 'poster_title',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '请输入海报标题进行搜索'
        },
        {
            label: '创建人',
            name: 'create_uid',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone}) `;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        }
    ];
});
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'title',
        label: '标题',
        width: 200
    },
    {
        label: '海报',
        width: 80,
        render({ row, column, index }) {
            const slotError = () => (
                <div class="image_slot">
                    <ElIcon>
                        <icon-picture />
                    </ElIcon>
                </div>
            );
            return (
                <div class="cusInfo">
                    <ElImage
                        preview-src-list={[row.poster_url]}
                        preview-teleported={true}
                        style="width: 46px; height: 61px"
                        vSlots={{ error: slotError }}
                        src={row.poster_url}
                        fit="cover"
                        class="avatar"></ElImage>
                </div>
            );
        }
    },
    {
        label: '下载次数',
        render({ row, column, index }) {
            return <span>{row.download_num || 0}</span>;
        }
    },
    {
        label: '发送次数',
        render({ row, column, index }) {
            return <span>{row.send_num || 0}</span>;
        }
    },
    {
        label: '所属分组',
        render({ row, column, index }) {
            return <span>{row.group_name || '--'}</span>;
        }
    },
    {
        label: '创建人',
        render({ row, column, index }) {
            return <span>{row.created_name || '--'}</span>;
        }
    },
    {
        label: '创建时间',
        width: 180,
        render({ row, column, index }) {
            return <span>{row.created_at || '--'}</span>;
        }
    },
    {
        prop: 'operate',
        label: '操作',
        align: 'left',
        fixed: 'right',
        width: 260,
        isOperate: true,
        renderOperate({ row, column, index }) {
            return (
                <div class="handle">
                    <ElButton size="small" onClick={() => submitFun(row, 1)} vAuth={'EDIT_PT'}>
                        编辑
                    </ElButton>
                    <ElButton size="small" onClick={() => submitFun(row, 2)} vAuth={'DEL_PT'}>
                        下载
                    </ElButton>
                    <ElButton size="small" onClick={() => submitFun(row, 3)} vAuth={'PREVIEW_PT'}>
                        预览
                    </ElButton>
                    <ElButton size="small" onClick={() => submitFun(row, 4)} vAuth={'DEL_PT'}>
                        删除
                    </ElButton>
                </div>
            );
        }
    }
];
const fetchApi = () => {
    // 获取文件列表
    return posterList;
};
//表格的高度
const getTableH = () => {
    myTableRef.value.getTableH();
};

// 删除的api
const delApiFun = () => {
    store.commit('user/setApiList', [
        '/scrm-api/console/market/poster/del',
        '/scrm-api/console/market/poster/list',
        '/scrm-api/console/tenant/group/getLists'
    ]);

    batchDel({
        poster_ids: posterIds.value,
        poster_type: tabIndex.value + 1
    }).then(async (r: any) => {
        myTableRef.value.clearSelection();
        DeletBoxRef.value.appDialog.visible = false;
        ElMessage.success('删除成功');
        myTableRef.value.getTable().clearSelection();
        myTableRef.value.reload();
        await GroupingRef.value.getGroup(posters.value);
        state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
    });
};
// 批量删除
const delItem = () => {
    DeletBoxRef.value.appDialog.visible = true;
    DeletBoxRef.value.appDialog.submit = delApiFun;
};

const search = (data: any) => {
    myTableRef.value.clearSelection();
    currentParams.value = {
        ...deepCopy(defaultParams),
        ...data,
        group_id: group_id.value,
        poster_type: tabIndex.value + 1
    };
    state.searchParams = deepCopy(currentParams.value);
};
const reset = (v?: any) => {
    myTableRef.value.clearSelection();
    currentParams.value = {
        ...deepCopy(defaultParams),
        group_id: group_id.value,
        poster_type: tabIndex.value + 1
    };
    state.searchParams = deepCopy(currentParams.value);
};
// 选择分组
const changeGroup = (val: any) => {
    store.commit('user/setApiList', [
        '/scrm-api/console/market/poster/list',
        '/scrm-api/console/tenant/group/getLists'
    ]);
    myTableRef.value.clearSelection();
    if (val.id === group_id.value) {
        GroupingRef.value.getGroup();
    } else {
        group_id.value = val.id;
    }
    currentParams.value = {
        ...deepCopy(defaultParams),
        ...currentParams.value,
        group_id: group_id.value,
        poster_type: tabIndex.value + 1
    };
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
};

const toCreate = () => {
    router.push({
        path: `/content/highMaterial/poster/posterDetail?type=${+tabIndex.value}`,
        query: {
            group_id: group_id.value === 'all' ? 0 : group_id.value,
            group_type: posters.value,
            val: tabIndex.value + 1
        }
    });
};

// 选择海报列表类型
const chooseTabIndex = (val: any) => {
    store.commit('user/setApiList', [
        '/scrm-api/console/market/poster/list',
        '/scrm-api/console/tenant/group/getLists'
    ]);
    myTableRef.value.clearSelection();
    tabIndex.value = +strTabIndex.value;
    const type = tabIndex.value ? 10 : 9;
    posters.value = type;
    state.searchParams.group_id = 'all';
    sessionStorage.setItem('posterType', JSON.stringify(posters.value));
    state.searchParams.poster_type = tabIndex.value == 0 ? 1 : 2;
    // GroupingRef.value.toggleGroupTab(type, 'all');
};

// 选中的数据 我的表格
const getSelectMyTable = (val: any) => {
    posterIds.value = getSetionId('id', val);
};

// 批量下载
const batchDown = () => {
    batchDownload({
        poster_ids: posterIds.value,
        poster_type: tabIndex.value + 1
    }).then((r: any) => {
        myTableRef.value.clearSelection();
        ElMessage.success('批量下载成功');
        window.location = r.file_url;
    });
};
const submitFun = (val: any, type: number) => {
    switch (type) {
        case 1: //编辑
            router.push({
                path: `/content/highMaterial/poster/posterDetail`,
                query: {
                    id: val.id,
                    group_id: group_id.value,
                    group_type: posters.value,
                    val: tabIndex.value + 1,
                    type: 'edit'
                }
            });
            break;
        case 2: //下载
            downStat({ poster_id: val.id }).then((res: any) => {
                // myTableRef.value.clearSelection();
                ElMessage.success('下载成功');
                myTableRef.value.reload();
            });
            downFile(val.poster_url, val.title + val.created_at);
            break;
        case 3: //预览
            PreviewBoxRef.value.drawerData.show = true;
            itemInfo.value = val;
            break;
        default:
            DeletBoxRef.value.appDialog.visible = true;
            DeletBoxRef.value.appDialog.title = '删除提示';
            DeletBoxRef.value.appDialog.submit = delApiFun;
            itemInfo.value = val;
            posterIds.value = [val.id];
    }
};

onMounted(async () => {
    isOnMountedFlag.value = true;
    store.commit('user/setApiList', [
        '/scrm-api/console/tenant/group/getLists',
        '/scrm-api/console/market/poster/list'
    ]);
});

onActivated(async (val: any) => {
    store.commit('user/setApiList', [
        '/scrm-api/console/tenant/group/getLists',
        '/scrm-api/console/market/poster/list'
    ]);
    const type = tabIndex.value ? 10 : 9;
    if (route.query?.groupId) {
        if (group_id.value == route.query?.groupId) {
            GroupingRef.value.changeGroup({ id: Number(route.query?.groupId) });
        } else {
            group_id.value = Number(route.query?.groupId);
        }
        defaultParams.group_id = Number(route.query?.groupId);
        state.searchParams.group_id = Number(route.query?.groupId);
        sessionStorage.setItem('posterType', JSON.stringify(posters.value));
        state.searchParams.poster_type = tabIndex.value == 0 ? 1 : 2;

        // 这里是处理从新增页面携带poster_type参数接不正确的问题
        // posters.value = route.query?.poster_type === '2' ? 10 : 9;
        // await GroupingRef.value.getGroup(posters.value);
        // GroupingRef.value.changeGroup({ id: Number(route.query?.groupId) });
        // 这里是处理当前选中不正确的问题
        // GroupingRef.value.setCurrentSelectId({ id: group_id.value });
        // 这里是因为postertype类型，如果是2的话，代表企业海报
        // 企业海报的tabs栏的参数用的是1，所以做一次修改。
        // 如果是poster_type1的话，代表我的海报，对应的tabs参数为0
        tabIndex.value = route.query?.poster_type == '1' ? 0 : 1;
        strTabIndex.value = route.query?.poster_type === '2' ? '1' : '0';
        router.push({ query: {} });
    } else {
        await GroupingRef.value.getGroup(posters.value);
        GroupingRef.value.setCurrentSelectId({ id: group_id.value });
    }
    myTableRef.value.clearSelection();
    currentParams.value = {
        ...deepCopy(defaultParams),
        ...currentParams.value,
        group_id: group_id.value,
        poster_type: tabIndex.value + 1
    };
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
});
</script>

<style lang="scss" src="./style.scss" scoped>
.tabs_box {
    :deep .el-tabs__item {
        margin: 0 20px;
    }
}

.control-btn-box {
    text-align: right;
    margin: 15px 15px 0;
}
</style>
